const express = require('express')

const BookModel = require('../models/BookModel')

const router = express.Router()

router.get('/list',(req,res)=>{
    BookModel.find((error,data)=>{
        if(error){
            res.render('book/error',{errorMsg:'获取图书列表失败'})
        }else{
            res.render('book/list',{books:data})
        }
    })
})

router.get('./toUpdate/:id',(req,res)=>{
    const {id} = req.params
    BookModel.findById(id,(error,data)=>{
        if(error){
            res.render('book/error',{errorMsg:'获取图书失败'})
        }else{
            res.render('book/addOrUpdate',{book:data})
        }
    })
})

router.get('/toAdd',(req,res)=>{
    const book = {
        name:'',
        author:'',
        price:0
    }
    res.render('book/addOrUpdate',{book})
})






router.post('/add',(req,res)=>{
    const book = req.body
    BookModel.create(book,(error,data)=>{
        if(error){
            res.render('book/error',{errorMsg:'添加图书失败'})
        }else{
            res.redirect('/book/list')
        }
    })
})


router.post('/update',(req,res)=>{
    const book =req.body

    BookModel.updateOne({_id:book.id},book,(error,data)=>{
        if(error){
            res.render('book/error',{errorMsg:'修改图书失败'})
        }else{
            res.redirect('/book/list')
        }
    })
})


router.get('/remove/:id',(req,res)=>{
    const {id} = req.params
    BookModel.deleteOne({_id:id},(error,data)=>{
        if(error){
            res.render('book/error',{errorMsg:'删除图书失败'})
        }else{
            res.redirect('/book/list')
        }
    })
})

module.exports = router